import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:encrypt/encrypt.dart';

// import 'dart:convert';
class PasswordEncryptor {

//随机生成32位的字符串
 
static String generateRandomString() {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  final random = Random();
  String result = '';
  for (int i = 0; i < 32; i++) {
    result += characters[random.nextInt(characters.length)];
  }
  print('result----------: $result');
  return result;
}

// 随机生成aes 密钥
static Key generateAesKey() {
   
  return Key.fromBase64(base64.encode(utf8.encode(generateRandomString())));
}

// 加密base64
static String encryptBase64(String message) {
  final str = base64Encode(utf8.encode(message));
  print('result----: $str');
 return str;
}

// 解密base64
static Uint8List decryptBase64(String str) {
  return base64.decode(str);
}

// 使用密钥对数据进行加密
static String encryptWithAes(String aeskey,String message) {

  final key = Key.fromUtf8(aeskey);
  final iv = IV.fromLength(16);

  final encrypter = Encrypter(AES(key,mode: AESMode.ecb,padding: 'PKCS7'));
 // final jsonString = jsonEncode(message);
  final encrypted = encrypter.encrypt(message, iv: iv);
  final decrypted = encrypter.decrypt(encrypted, iv: iv);
  print('原始数据--$message');
  print('解密---$decrypted'); // Lorem ipsum dolor sit amet, consectetur adipiscing elit
  print('加密---${encrypted.base64}');
  print('加密base64---${utf8.encode(encrypted.base64)}');
//  decryptWithAes(encrypted.base64);// R2xvY2FsaG9zdCBhdCB0aGUgbW9yZSBpbWFnZSBib3Ro
  return encrypted.base64;
}

//使用密钥对数据进行解密
static String decryptWithAes(String aeskey,String message) {
  final key = Key.fromUtf8(aeskey);
  final iv = IV.fromLength(16);

  final encrypter = Encrypter(AES(key,mode: AESMode.ecb,padding: 'PKCS7'));
  final encrypted = Encrypted.fromBase64(message);
  final decrypted = encrypter.decrypt(encrypted, iv: iv);
  print('加密数据--$message');
  print('解密结果---$decrypted');
  return decrypted;
}
}
